import { FC, useMemo } from 'react';
import { Button, Input, InputProps } from 'antd';
import { CloseCircleOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import ClassNames from 'classnames';

import Dialog from './dialog';

import './index.less';
import { InputModalProps, RequestMethod } from '../interface';

import { triggerConvertDisplayValue } from '../triggerPlugin';
import { useVisible } from '@/biz-components/modals/hooks';

const InputModal: FC<InputModalProps> = ({
  convertDisplayValue,
  disabled,
  value,
  className,
  onChange,
  dialogProps,
  displayKey,
  url,
  method,
}) => {



  const { isMultiple } = dialogProps || {};

  const [visible, showModal, hiddenModal] = useVisible();

  const handleClick = () => {
    showModal();
  };

  const handleCancel = () => {
    hiddenModal();
  };

  const triggerChange = (changedValue: InputModalProps['value']) => {
    onChange?.(changedValue);
  };

  const handleClear = () => {
    triggerChange(undefined);
  };

  const handleOk = (selectedRow: any) => {
    triggerChange(isMultiple ? (value || []).concat(selectedRow) : selectedRow[0]);
  };

  const displayValue = useMemo<InputProps['value']>(() => {
    return displayKey
      ? value?.[displayKey]
      : triggerConvertDisplayValue(convertDisplayValue, value);
  }, [value, displayKey]);

  return (
    <>
      <Input
        value={displayValue}
        disabled={disabled}
        readOnly
        className={ClassNames(className, 'input-modal')}
        addonAfter={
          <Button disabled={disabled} onClick={handleClick}>
            {displayValue ? <EditOutlined /> : <PlusOutlined />}
          </Button>
        }
        suffix={
          displayValue ? (
            <CloseCircleOutlined onClick={handleClear} className="ant-input-clear-icon" />
          ) : null
        }
      />
      <Dialog
        {...dialogProps}
        url={url}
        method={method}
        visible={visible}
        onCancel={handleCancel}
        onOk={handleOk}
      />
    </>
  );
};

InputModal.defaultProps = {
  method: RequestMethod.POST,
  dialogProps: {
    isMultiple: false,
  },
};

export default InputModal;
